package com.lanchong.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.lanchong.config.AlipayConfig;
import com.lanchong.pojo.OrderInfo;
import com.lanchong.pojo.User;
import com.lanchong.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Random;

@Slf4j
@Controller
public class TestController {
    @Resource
    private AlipayConfig alipayConfig;
    @Autowired
    private OrderService orderService;


    @RequestMapping("/pay-select")
    public String testPaySelect(@RequestParam("orderId") long orderId,  @RequestParam("goodsPrice") BigDecimal goodsPrice){
        return "mall/pay-select";
    }
    @GetMapping("/selectPayType")
    public String selectPayType(HttpServletRequest request, @RequestParam("orderId") long orderId, HttpSession session) {
        User user = (User) session.getAttribute("id");
        OrderInfo order = judgeOrderUserId(orderId, user.getId());

        request.setAttribute("id", orderId);
        request.setAttribute("goodsPrice", order.getGoodsPrice());
        return "mall/pay-select";
    }

    @GetMapping("/payPage")
    public String payOrder(HttpServletRequest request, @RequestParam("orderId") long orderId, HttpSession session) throws UnsupportedEncodingException {
       //MallUserVO mallUserVO = (MallUserVO) session.getAttribute(Constants.MALL_USER_SESSION_KEY);
        User user = (User) session.getAttribute("id");
        OrderInfo order = judgeOrderUserId(orderId, user.getId());
        request.setAttribute("id", orderId);
        request.setAttribute("goods_price", order.getGoodsPrice());
            request.setCharacterEncoding("utf-8");
            // 初始化
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGateway(), alipayConfig.getAppId(),
                alipayConfig.getRsaPrivateKey(), alipayConfig.getFormat(), alipayConfig.getCharset(), alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSigntype());
            // 创建API对应的request
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//            // 在公共参数中设置回调和通知地址
//            String url = "localhost" + request.getContextPath();
//            alipayRequest.setReturnUrl(url + "/returnOrders/" + order.getId() + "/" + user.getId() );
//            alipayRequest.setNotifyUrl(url + "/paySuccess?id=" + order.getId());

            // 填充业务参数

            // 必填
            // 商户订单号，需保证在商户端不重复
            String out_trade_no = String.valueOf(order.getId());
            // 销售产品码，与支付宝签约的产品码名称。目前仅支持FAST_INSTANT_TRADE_PAY
            String product_code = "FAST_INSTANT_TRADE_PAY";
            // 订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]。
            String total_amount = order.getGoodsPrice() + "";
            // 订单标题
            String subject = "支付宝测试";

            // 选填
            // 商品描述，可空
            String body = "商品描述";

            alipayRequest.setBizContent("{" + "\"out_trade_no\":\"" + out_trade_no + "\"," + "\"product_code\":\""
                    + product_code + "\"," + "\"total_amount\":\"" + total_amount + "\"," + "\"subject\":\"" + subject
                    + "\"," + "\"body\":\"" + body + "\"}");
            // 请求
            String form;
            try {
                form = alipayClient.pageExecute(alipayRequest).getBody();//调用SDK生成表单
                request.setAttribute("form", form);
            } catch (AlipayApiException e) {
                log.error(e.getMessage(), e);
                ;
            }
            return "mall/alipay";
        }

    /**
     * 判断订单关联用户id和当前登陆用户是否一致
     *
     * @param orderId 订单编号
     * @param userId  用户ID
     * @return 返回订单对象
     */
    private OrderInfo judgeOrderUserId(long orderId, long userId) {
        OrderInfo order = orderService.getOrderByUserIdOrdersId(orderId,userId);
        // 判断订单userId
        if (order == null || !order.getUserId().equals(userId)) {
//            throw new BusinessException("当前订单用户异常");
            return null;
        }
        return order;
    }
}
